package code.whmmm.util.spring.quartz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p><b>
 *
 * </b></p>
 * <br/>
 * 创建时间: 8/14/2019 1:33 PM
 *
 * @author Zero
 */
@Component
public class QuartzBeanManager implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired(required = false)
    private List<QuartzJob> jobList;
    @Autowired(required = false)
    private PersZeroQuartzSchedule schedule;


    private static AtomicBoolean initialed = new AtomicBoolean(false);

    public void initQuartz() {
        // 只能初始化一次！
        if (initialed.get()) {
            return;
        }
        initialed.set(true);
        if (jobList != null && jobList.size() > 0) {
            for (QuartzJob it : jobList) {
                if (it.isEnable()) {
                    schedule.startJob(it);
                }
            }
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent，他就是老大.
       /* if (event.getApplicationContext().getParent() == null) {
            initQuartz();
        }*/

        initQuartz();

    }
}
